import React, {useEffect, useState} from 'react';
import {Link, useHistory} from "react-router-dom";
import {Modal,List, Drawer, Button, Toast,PullToRefresh,InputItem,DatePicker} from 'antd-mobile';



import Txt from "../../../components/txt/Txt";

import './index.less';
import man from '../../../libs/img/user/man.png';
import woman from '../../../libs/img/user/woman.png';
import http from "../../../model/http"; 
import Header from "../../../components/header/Header";
import {dateFormat} from '../../../model/code';
import More from "./more/index"
let page = 1;
let list=[]
let param = {}
const h = document.documentElement.clientHeight - 70;

function CustomerInventory() { 
    
    const history = useHistory();
    // const [list,setList] = useState([]);
    const [load,setLoad] = useState(false);
    const [listCount,setListCount] = useState(0)
    const [sliderData,setSliderData] = useState([])

    const [open ,setOpen] =useState(false)

    const [filterAllCount,setFilterAllCount] = useState(0)

    const [jurisdiction, setJurisdiction] = useState({})
    
    // let data= [
    //     {
    //         title:"营销词1",
    //         titleId:"1",
    //         type:"1",
    //         list:[
    //             {
    //                 id:"1",
    //                 name:"0"
    //             },
    //             {
    //                 id:"2",
    //                 name:"100"
    //             },
               
    //         ]
    //     },


    //     {
    //         title:"营销词1",
    //         titleId:"1",
    //         type:"2",
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },
        
    //     {
    //         title:"日期选择",
    //         titleId:"3",
    //         type:"3",
    //         start:new Date(),
    //         end:new Date(),
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },

    //     {
    //         title:"日期选择",
    //         titleId:"4",
    //         type:"3",
    //         start:new Date(),
    //         end:new Date(),
    //         list:[
    //             {
    //                 id:"1",
    //                 value:"0"
    //             },
    //             {
    //                 id:"2",
    //                 value:"100"
    //             },
               
    //         ]
    //     },
     
        
    //  ]

    let [filterData,setFilterData] = useState([])
    
    

    const getList = ()=>{
        (async ()=>{
        setLoad(true);
            
        // http://wxwork.gzsg.cn/wxwork/customersearch/batchSearchNew?hosId=1&userId=XiongdLiDi&managerId=1001809
      
            const _list = await http.post_all('/customersearch/batchSearchNew',param)
            setTimeout(()=>{setLoad(false)},800)
            setListCount(_list.count)
            if(!_list.resultData.length) return
            page++
            param.page =page
            console.log("page",page)
            list = [...list,..._list.resultData]

      
        
       

        })()
        
    }

    const getSliderData=async ()=>{
        //http://wxwork.gzsg.cn/wxwork/customersearch/getCondition?searchHosId=1&userId=xxx&managerId=xxx&hosId=1
          
        let list = window.localStorage.getItem('myFilterData') ? JSON.parse(window.localStorage.getItem('myFilterData')) : []
        
        if(list.length == 0){
            const slderList = await http.post('/customersearch/getCondition',{
                searchHosId:"1"
            })
            console.log("setList",slderList.resultData)
            slderList.resultData.forEach(item=>{
                if(item.type == 3){
                    item.start=""
                    item.end=""
                }
            })
            setFilterData(slderList.resultData)
            getAllCound([])
            
    
        }else{
            let newArr = []
            list.forEach(item=>{
                if(item.type == 1){
                   
                    let btnArrList=[]
                    item.list.forEach( k=>{
                        if(k.selected){
                            btnArrList.push( k.value )
                        }
                    
                    } )
                    item.selectedData=btnArrList.join(",")
                    if(btnArrList.length>0){
                        newArr.push(item)
                    }
                    


                  
                }

                if(item.type == 2){
                    if(item.hasOwnProperty("start") && item.hasOwnProperty("end")){
                        newArr.push(item)
                    }
                }
                
                if(item.type == 3){
                    if(item.start && item.end){
                         
                        item.start = new Date(item.start)
                        item.end = new Date(item.end)
                        newArr.push(item)
                    }


                }


            })

            setFilterData(list)
            getAllCound(newArr)

           

        }

        
    }

    const done = ()=>{
        console.log("done")
        setOpen(true)
        getSliderData()
    }

    const sureSubmit=()=>{

        let myFilterData = JSON.parse(JSON.stringify(filterData))

        window.localStorage.setItem("myFilterData",JSON.stringify(myFilterData))
       
        let newArr = []
        
        myFilterData.forEach( m=>{
            if(m.type == 2 ){
               if(m.hasOwnProperty("start")||m.hasOwnProperty("end") ){
                  delete m.list
                  newArr.push(m)
               }
            }
             
            if( m.type == 3 ){     
                
                if(m.start && m.end){
                    m.start = (m.start+"").slice(0,10)
                    m.end = (m.end+"").slice(0,10)
                    delete m.list
                    newArr.push(m)
                } 
            }

            if(m.type == 1){
                let btnArrList=[]
                m.list.forEach( k=>{
                    if(k.selected){
                        btnArrList.push( k.value )
                    }
                   
                } )
                m.selectedData=btnArrList.join(",")

                if(btnArrList.length>0){
                    delete m.list
                    newArr.push(m)
                }
             
            }
        } )
        
        console.log("finalDate",newArr)

     



        setOpen(false)
        page=1
        list=[]
        setListCount(0)

        param={
            // flag:1,
            page:page,
            items:10,  
            filterData:newArr
        }

        setTimeout(()=>{
           getList()
        },100)
       


    }

    const currentExchange =(id,item)=>{
        console.log("id",id) //外层id
        console.log("item",item) // 内层数组
        
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                // n.start=new Date(n.start) 
                // n.end = new Date(n.end)

                if(n.start && n.end){
                    n.start=new Date(n.start)
                    n.end=new Date(n.end)
                }else{
                    n.start=""
                    n.end=""
                }
            }
           

            n.list.forEach((m)=>{ //内层
                 if(n.titleId == id){
                     if(m.id == item.id){
                         if(m.selected){
                             m.selected= false
                         }else{
                             m.selected=true
                         }
                     }
                 }
            })
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)
        getAllCound(list)
    }

    const reSet=()=>{
        // let list= JSON.parse(JSON.stringify(filterData))
        // list.forEach((n)=>{ //外层
        //     n.list.forEach((m)=>{ //内层           
        //             m.selected=false 
        //     })
        // })
        // console.log("filterData",list) // 内层数组
        // setFilterData(list)
        
        window.localStorage.removeItem("myFilterData")
        getSliderData()
        getAllCound([])
 

    }

    const type2Change1 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.start && n.end){
                    n.start=new Date(n.start)
                    n.end=new Date(n.end)
                }else{
                    n.start=""
                    n.end=""
                }
            }
            
            if(n.type == 2){
                if(n.titleId == id){
                    // if(!n.end){ n.end= parseInt(n.list[1].value)||0  }
                    // if(parseInt(v)>parseInt(n.end)){
                    //     n.start =parseInt(v) ||0
                    //     n.end =parseInt(v) ||0
                        
                    //     if(parseInt(v)> parseInt(n.list[1].value)){
                    //        n.start= parseInt(n.list[1].value)||0
                    //        n.end= parseInt(n.list[1].value)||0
                    //     }

                    // }else{
                    //     n.start =parseInt(v) ||0
                    //     if(parseInt(v)> parseInt(n.list[1].value)){
                    //         n.start= parseInt(n.list[1].value) ||0
                    //         n.end= parseInt(n.list[1].value) ||0
                    //      }
 
                    // }        
                    n.start=parseInt(v) ||0
                    if(parseInt(v)> parseInt(n.list[1].value)){
                            n.start= parseInt(n.list[1].value) ||0
                    }
                }
            }  
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)

        let currentItem = list.filter(k=>{
            return k.titleId == id
        })[0]

        if(currentItem.type == 2){
            if(currentItem.start && currentItem.end){
                if(parseInt(currentItem.start)<= parseInt(currentItem.end)  ){
                 getAllCound(list)
                }else{
                    Toast.fail("输入有误!")
                }
             }
        }

       
       
        

    }

    const type2Change2 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.start && n.end){
                    n.start=new Date(n.start)
                    n.end=new Date(n.end)
                }else{
                    n.start=""
                    n.end=""
                }
            }
            if(n.type == 2){
                if(n.titleId == id){
                    n.end =parseInt(v) || 0
                    
                    if(parseInt(v)> parseInt(n.list[1].value)){
                        n.end= parseInt(n.list[1].value) || 0
                    }



                    // if(parseInt(v)<parseInt(n.start)){
                    //     n.start =parseInt(n.v) || 0
                    //     n.end =parseInt(n.v) || 0
                        
                    //     if(parseInt(v)> parseInt(n.list[1].value)){
                    //         n.end= parseInt(n.list[1].value) || 0
                           
                    //      }
 

                    // }
                    // else{
                    //      n.start =parseInt(n.start) || 0
                    //      n.end =parseInt(v) || 0
                    //     if(parseInt(v)> parseInt(n.list[1].value)){
                    //         n.end= parseInt(n.list[1].value) || 0
                    //     }


 
                    // }
                }
            }

           
           
           
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)

        let currentItem = list.filter(k=>{
            return k.titleId == id
        })[0]

        if(currentItem.type == 2){
            if(currentItem.start && currentItem.end){
                if(parseInt(currentItem.start)<= parseInt(currentItem.end)  ){
                 getAllCound(list)
                }else{
                    Toast.fail("输入有误!")
                }
             }
        }
       
    }

    const type3Change1 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.titleId == id){

                    // n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                    // n.end = new Date(n.end)
                    
                    if(n.start && n.end){
                        if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() >  new Date(n.end).getTime() ){
                      
                            n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                            n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                            }else{
                                n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                                n.end = new Date(n.end)
                        }

                    }else{
                        n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                        if(n.end){
                            n.end = new Date(n.end)
                              //-----
                            if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() >  new Date(n.end).getTime() ){
                      
                                n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                                n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                                }else{
                                    n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                                    n.end = new Date(n.end)
                            }
                            //-----


                        }else{
                            n.end =""
                        }
                       
                    }

                }else{
                    if(n.start){
                        n.start=new Date(n.start)
                    }else{
                        n.start=""
                    }

                    if(n.end){
                        n.end=new Date(n.end)
                    }else{
                        n.end=""
                    }
                }
             
               
            }

          
        })
        

        console.log("filterData",list) // 内层数组
        setFilterData(list)
        getAllCound(list)
    }

    const type3Change2 =(v,id)=>{
        console.log("id",id)
        let list= JSON.parse(JSON.stringify(filterData))
        list.forEach((n)=>{ //外层
            if(n.type == 3){
                if(n.titleId == id){
          
                    // n.end=new Date(dateFormat(v,'yyyy-MM-dd')) 
                    // n.start = new Date(n.start)

                if(n.start && n.end){
                    if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() <  new Date(n.start).getTime() ){
                       
                        n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                        n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                    }else{
                        n.end=new Date(dateFormat(v,'yyyy-MM-dd')) 
                        n.start = new Date(n.start)
                    }

                }   else{

                    n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                   
                    if(n.start){
                        n.start = new Date(n.start)
                         // -----
                         if( new Date(dateFormat(v,'yyyy-MM-dd')).getTime() <  new Date(n.start).getTime() ){
                       
                            n.start=new Date(dateFormat(v,'yyyy-MM-dd')) 
                            n.end =new Date(dateFormat(v,'yyyy-MM-dd')) 

                        }else{
                            n.end=new Date(dateFormat(v,'yyyy-MM-dd')) 
                            n.start = new Date(n.start)
                        }           
                         // ----

                    }else{
                        n.start=""
                    }
  
                 } 

                }else{
                    if(n.start){
                        n.start=new Date(n.start)
                    }else{
                        n.start=""
                    }

                    if(n.end){
                        n.end=new Date(n.end)
                    }else{
                        n.end=""
                    }
                }
              
            }

           
           
        })
        console.log("filterData",list) // 内层数组
        setFilterData(list)
        getAllCound(list)
    }

    const getAllCound =async (data) =>{
        //http://wxwork.gzsg.cn/wxwork/customersearch/batchSearchNewCount?hosId=1&userId=XiongdLiDi&managerId=1001809

        let myFilterData = JSON.parse(JSON.stringify(data))
       
        let newArr = []
        
        myFilterData.forEach( m=>{
            if(m.type == 2 ){
               if(m.hasOwnProperty("start")||m.hasOwnProperty("end") ){
                  delete m.list
                  newArr.push(m)
               }
            }
             
            if( m.type == 3 ){     
                
                if(m.start && m.end){
                    m.start = (m.start+"").slice(0,10)
                    m.end = (m.end+"").slice(0,10)
                    delete m.list
                    newArr.push(m)
                } 
            }

            if(m.type == 1){
                let btnArrList=[]
                m.list.forEach( k=>{
                    if(k.selected){
                        btnArrList.push( k.value )
                    }
                   
                } )
                m.selectedData=btnArrList.join(",")

                if(btnArrList.length>0){
                    delete m.list
                    newArr.push(m)
                }
             
            }
        } )
        
        console.log("finalDate",newArr)

        const _list = await http.post_all('/customersearch/batchSearchNewCount',{
            filterData:newArr
        })

        setFilterAllCount(_list.count)




        





    }

    useEffect(()=>{  
        setJurisdiction(sessionStorage.getItem('doctorJurisdiction')?JSON.parse(sessionStorage.getItem('doctorJurisdiction')):'')
        
        let lists = window.localStorage.getItem('myFilterData') ? JSON.parse(window.localStorage.getItem('myFilterData')) : []
        let newArr =[]
        lists.forEach(item=>{
            if(item.type == 1){
            //    if(item.selected){
            //        newArr.push(item)
            //    }
                    
                    let btnArrList=[]
                    item.list.forEach( k=>{
                        if(k.selected){
                            btnArrList.push( k.value )
                        }
                    
                    } )
                    item.selectedData=btnArrList.join(",")
                    if(btnArrList.length>0){
                        newArr.push(item)
                    }
                    
               
            }

            if(item.type == 2){
                if(item.hasOwnProperty("start") && item.hasOwnProperty("end")){
                    newArr.push(item)
                }
            }

            if(item.type == 3){
                if(item.start && item.end){
                    newArr.push(item)
                }


            }
        })



        list=[]
        page=1
        param={
            // flag:history.location.state.flag, 
            page:page,
            items:10,  
            filterData:newArr
        }
        
       
        list.length || getList();


        // return ()=>{
        
        // page=1
        // }
        // eslint-disable-next-line
    },[])
      
    const toDeails=(item)=>{
       history.push(`/user/details?isBind=${1}&outUserId=${item.customerCrmId}&entryIsHome=${1}`, item); //跳转到客户详情页面
    }
   

   

    return (
        <div className='v-user-userHomeList'>
         
            
            {/* <More done={done}></More> */}
            
            {/* 弹框 */}
            { 
               open ? (
                    <div>
                    <div onClick={ ()=>{ 
                        setOpen(false) 
                        
                     } } className='my_masker'>
                    </div>
                    <div className='masker_content'>
                        <div className='scroll'>
                        {
                            filterData.map((item,index)=>(
                                <div className='masker_item' style={{width:'100%'}}>
                                     <div className='title'>{item.title}</div>
                                       {
                                           item.type==1 ? (
                                                <div className='tagBox'> 
                                                {
                                                    item.list.map((item1,index)=>(
                                                    <div className={ item1.selected?'active' :'tag' } onClick={(  )=>{ currentExchange(item.titleId,item1) } }   >{item1.name}</div>
                                                    ))
                                                }                 
                                            </div>
                                           ) : null
                                       }

                                       {
                                           item.type==2 ? (
                                                <div className='tagBox'> 
                                                <div style={{flex:1}}>
                                                    <InputItem type='number'   
                                                        value={ item.start}  
                                                        placeholder = {'最小值'+item.list[0].value }
                                                        onChange={(v) => {  type2Change1(v,item.titleId)  }} 
                                                    /> 
                                                </div>
                                                <div style={{marginTop:"12px",fontSize:"14px"}}>至</div>
                                                <div style={{flex:1,}}>
                                                <InputItem type='number'   
                                                    value={ item.end}  
                                                    placeholder = {'最大值'+item.list[1].value }
                                                    onChange={(v) => { type2Change2(v,item.titleId)}} 
                                                /> 
                                                </div>
                                                 
                                                 

                                            </div>
                                           ) : null
                                       }

                                           {
                                            item.type==3 ? (
                                                <div className='tagBox'> 
                                                <div style={{flex:1}}>
                                                <DatePicker mode="date" value={item.start}  onChange={d1=>{  type3Change1(d1,item.titleId) }}>  
                                                    <List.Item arrow="horizontal"></List.Item>
                                                    </DatePicker>  
                                                </div>
                                                <div style={{marginTop:"12px",fontSize:"14px"}}>至</div>
                                                <div style={{flex:1,}}>
                                                <DatePicker mode="date" value={item.end}    onChange={d2=>{ type3Change2(d2,item.titleId)  }}>  
                                                    <List.Item arrow="horizontal"></List.Item>
                                                    </DatePicker> 
                                                </div>
                                                 
                                                 

                                            </div>
                                           ) : null
                                       }



                                    

                                </div>
                            ))
                        } 

                        </div> 

                        <div className='masker_btn'>
                            <div onClick={()=>{ reSet() }} style={{textAlign:'center',lineHeight:'34px', color:'black',width:'90px',height:'34px',borderRadius:'60px',border:'1px solid #c8c8c8',fontSize:'16px'}}>重置</div>
                            <div onClick={()=>{ sureSubmit()   } } style={{marginLeft:'12px', textAlign:'center',lineHeight:'34px', color:'#ffffff',backgroundColor:'#108ee9', width:'90px',height:'34px',borderRadius:'60px',border:'1px solid #108ee9',fontSize:'16px'}}>确定({filterAllCount})人</div>
                        </div>
                    </div>
                </div>

               ) : null
            
            }
           
           
            <div className='body-background-div'></div>
             
            <Button onClick={ ()=>{ done()  }} style={{ backgroundColor:"#108ee9",color:"#ffffff",fontSize:"16px" }}>筛选</Button>

            <PullToRefresh direction='up' onRefresh={getList} refreshing={load} style={{height:h, overflow:'auto'}}>
                 
                {list.map((item,idx)=>(
                    <div key={idx} className='userList-row g-flex g-x-between g-mt32'
                    onClick={toDeails.bind(this,item)}
                    style={{padding: '0.25rem 0.2rem', backgroundColor: '#FFFFFF'}}>
                        <div className='g-flex' >
                            <img src={item.sex=='1'?woman:man} style={{width:'1rem',height:'1rem'}} className='g-round' alt="UserImg"/>
                            <div className='g-ml20 g-f24 g-c-999'>
                                <p className='g-f30 g-c-333 '>
                                    <span style={{fontSize:'0.32rem',fontWeight:'bold'}}>{item?.customerCrmName}</span>
                                </p> 
                                <p className='g-mt24'>卡号：<span>{item?.mzcode}</span></p>
                                <p className='g-mt12' style={{lineHeight:'0.4rem'}}>所属咨询：{item.xcname?item.xcname:'暂无'}</p>
                                <p className='g-mt12' style={{lineHeight:'0.4rem'}}>开发人：{item.dwname?item.dwname:'暂无'}</p> 
                            </div>
                        </div> 
                        
                    </div>
                    
                ))}
                {list.length >= listCount? <div className='test-color'>暂无更多数据</div> : ''}
            </PullToRefresh>
            
          


            <Header/>
           
            
           

        </div>
    )
}
export default CustomerInventory;

// "customerCrmId": "20160504020458953000", 
// "sex": 1, 
// "xcname": "高慧清", 
// "dwname": "王进福", 
// "mzcode": "160215111", 
// "age": 21, 
// "customerCrmName": "李甜"